import { create } from 'zustand';
import { devtools } from 'zustand/middleware';

// 检查是否在浏览器环境中
const isBrowser = typeof window !== 'undefined';

let db: any = null;

// 只在Node.js环境中初始化数据库
if (!isBrowser) {
  try {
    db = require('../database/db').default;
  } catch (error) {
    console.log('数据库未初始化，使用模拟数据');
  }
}

export interface Setting {
  key: string;
  value: string;
  updatedAt: string;
}

export interface ProxyConfig {
  id: string;
  host: string;
  port: number;
  username?: string;
  password?: string;
  isActive: boolean;
  createdAt: string;
}

interface SettingState {
  settings: Record<string, string>;
  proxies: ProxyConfig[];
  loading: boolean;
  error: string | null;
  
  // Actions
  fetchSettings: () => Promise<void>;
  updateSetting: (key: string, value: string) => Promise<void>;
  getSetting: (key: string) => string;
  
  // Proxy actions
  fetchProxies: () => Promise<void>;
  addProxy: (proxy: Omit<ProxyConfig, 'id' | 'createdAt'>) => Promise<void>;
  updateProxy: (id: string, updates: Partial<ProxyConfig>) => Promise<void>;
  deleteProxy: (id: string) => Promise<void>;
  toggleProxy: (id: string) => Promise<void>;
}

export const useSettingStore = create<SettingState>()(
  devtools(
    (set, get) => ({
      settings: {},
      proxies: [],
      loading: false,
      error: null,

      fetchSettings: async () => {
        set({ loading: true, error: null });
        try {
          if (isBrowser || !db) {
            // 浏览器环境，使用默认设置
            const defaultSettings = {
              autoLogin: 'true',
              autoSync: 'false',
              syncInterval: '30',
              maxRetries: '3',
              timeout: '30',
              language: 'zh_CN',
              storagePath: '/storage'
            };
            set({ settings: defaultSettings, loading: false });
          } else {
            const stmt = db.prepare('SELECT * FROM settings');
            const settings = stmt.all() as Setting[];
            const settingsMap = settings.reduce((acc, setting) => {
              acc[setting.key] = setting.value;
              return acc;
            }, {} as Record<string, string>);
            set({ settings: settingsMap, loading: false });
          }
        } catch (error) {
          set({ error: (error as Error).message, loading: false });
        }
      },

      updateSetting: async (key, value) => {
        set({ loading: true, error: null });
        try {
          const now = new Date().toISOString();
          
          if (isBrowser || !db) {
            // 浏览器环境，直接更新状态
            set(state => ({
              settings: { ...state.settings, [key]: value },
              loading: false
            }));
          } else {
            const stmt = db.prepare(`
              INSERT OR REPLACE INTO settings (key, value, updatedAt)
              VALUES (?, ?, ?)
            `);
            stmt.run(key, value, now);

            set(state => ({
              settings: { ...state.settings, [key]: value },
              loading: false
            }));
          }
        } catch (error) {
          set({ error: (error as Error).message, loading: false });
        }
      },

      getSetting: (key) => {
        return get().settings[key] || '';
      },

      fetchProxies: async () => {
        set({ loading: true, error: null });
        try {
          if (isBrowser || !db) {
            // 浏览器环境，使用模拟数据
            const mockProxies: ProxyConfig[] = [
              {
                id: '1',
                host: '192.168.1.100',
                port: 8080,
                username: 'user1',
                password: '******',
                isActive: true,
                createdAt: '2024-01-01'
              }
            ];
            set({ proxies: mockProxies, loading: false });
          } else {
            const stmt = db.prepare('SELECT * FROM proxies ORDER BY createdAt DESC');
            const proxies = stmt.all() as ProxyConfig[];
            set({ proxies, loading: false });
          }
        } catch (error) {
          set({ error: (error as Error).message, loading: false });
        }
      },

      addProxy: async (proxy) => {
        set({ loading: true, error: null });
        try {
          const id = Date.now().toString();
          const now = new Date().toISOString();
          const newProxy: ProxyConfig = {
            ...proxy,
            id,
            createdAt: now,
          };

          if (isBrowser || !db) {
            // 浏览器环境，直接更新状态
            set(state => ({
              proxies: [newProxy, ...state.proxies],
              loading: false
            }));
          } else {
            const stmt = db.prepare(`
              INSERT INTO proxies (id, host, port, username, password, isActive, createdAt)
              VALUES (?, ?, ?, ?, ?, ?, ?)
            `);
            stmt.run(
              newProxy.id,
              newProxy.host,
              newProxy.port,
              newProxy.username,
              newProxy.password,
              newProxy.isActive ? 1 : 0,
              newProxy.createdAt
            );

            set(state => ({
              proxies: [newProxy, ...state.proxies],
              loading: false
            }));
          }
        } catch (error) {
          set({ error: (error as Error).message, loading: false });
        }
      },

      updateProxy: async (id, updates) => {
        set({ loading: true, error: null });
        try {
          if (isBrowser || !db) {
            // 浏览器环境，直接更新状态
            set(state => ({
              proxies: state.proxies.map(proxy =>
                proxy.id === id ? { ...proxy, ...updates } : proxy
              ),
              loading: false
            }));
          } else {
            const updateFields = Object.keys(updates)
              .filter(key => key !== 'id')
              .map(key => `${key} = ?`)
              .join(', ');

            const stmt = db.prepare(`
              UPDATE proxies 
              SET ${updateFields}
              WHERE id = ?
            `);

            const values = [...Object.values(updates), id];
            stmt.run(...values);

            set(state => ({
              proxies: state.proxies.map(proxy =>
                proxy.id === id ? { ...proxy, ...updates } : proxy
              ),
              loading: false
            }));
          }
        } catch (error) {
          set({ error: (error as Error).message, loading: false });
        }
      },

      deleteProxy: async (id) => {
        set({ loading: true, error: null });
        try {
          if (isBrowser || !db) {
            // 浏览器环境，直接更新状态
            set(state => ({
              proxies: state.proxies.filter(proxy => proxy.id !== id),
              loading: false
            }));
          } else {
            const stmt = db.prepare('DELETE FROM proxies WHERE id = ?');
            stmt.run(id);

            set(state => ({
              proxies: state.proxies.filter(proxy => proxy.id !== id),
              loading: false
            }));
          }
        } catch (error) {
          set({ error: (error as Error).message, loading: false });
        }
      },

      toggleProxy: async (id) => {
        set({ loading: true, error: null });
        try {
          const proxy = get().proxies.find(p => p.id === id);
          if (proxy) {
            await get().updateProxy(id, { isActive: !proxy.isActive });
          }
          set({ loading: false });
        } catch (error) {
          set({ error: (error as Error).message, loading: false });
        }
      },
    }),
    {
      name: 'setting-store',
    }
  )
); 